<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="searchDeviceQuotaForm" :model="searchDeviceQuotaForm" label-width="80px">
        <el-col :span="5">
          <el-form-item style="margin-bottom: 5px;" label="设备号">
            <el-input v-model="searchDeviceQuotaForm.number" />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item style="margin-bottom: 5px;" label="标签">
            <el-input v-model="searchDeviceQuotaForm.tag" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item style="margin-bottom: 5px;" label="设备状态">
            <el-select v-model="searchDeviceQuotaForm.state" placeholder="请选择">
              <el-option
                v-for="item in stateOptions"
                :key="item.key"
                :label="item.label"
                :value="item.key"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-button style="margin-left:20px" type="primary" @click="searchPage">搜索</el-button>
        </el-col>
      </el-form>
    </div>
    <div class="table-container" :style="{width:'100%',overflow:'auto'}">
      <el-collapse v-model="activeName" accordion @change="handleChange">
        <template v-for="(item,idx) in deviceQuotaList">
          <el-collapse-item :key="idx" style="padding-bottom:0;" :name="idx">
            <template slot="title">
              <div style="width: 100%;">
                <el-row>
                  <el-col :span="2">设备ID: {{ item.id }}</el-col>
                  <el-col :span="3">设备号: {{ item.number }}</el-col>
                  <el-col :span="4">设备名: {{ item.name }}</el-col>
                  <el-col :span="5">绑定时间: {{ formatTime(item.bindTime) }}</el-col>
                  <el-col :span="2">{{ item.online ? '在线' : '离线' }}</el-col>
                  <el-col :span="4">监测状态：{{ item.status ? '开启' : '关闭' }}</el-col>
                </el-row>
                <el-row>
                  <el-col :offset="2" :span="10">设备简介: {{ item.description }}</el-col>
                </el-row>
              </div>
            </template>
            <el-row>
              <template v-if="item.quotaList.length>0">
                <el-table :data="item.quotaList" style="width:100%" border>
                  <el-table-column align="center" label="指标ID" width="80">
                    <template slot-scope="scope">
                      {{ scope.row.id }}
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="指标名" width="100">
                    <template slot-scope="scope">
                      {{ scope.row.name }}
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="主题" width="80">
                    <template slot-scope="scope">
                      {{ scope.row.subject }}
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="单位" width="80">
                    <template slot-scope="scope">
                      {{ scope.row.unit }}
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="键名" width="80">
                    <template slot-scope="scope">
                      {{ scope.row.valueKey }}
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="键值类型" width="80">
                    <template slot-scope="scope">
                      {{ scope.row.valueType }}
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="webhook" width="150">
                    <template slot-scope="scope">
                      {{ scope.row.webhook }}
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="参考值" width="100">
                    <template slot-scope="scope">
                      {{ scope.row.reference }}
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="操作" width="150" min-width="150">
                    <template slot-scope="scope">
                      <el-button type="primary" size="small" @click="handleUpdateDeviceQuota(scope)">修改</el-button>
                      <el-button type="danger" size="small" @click="handleDeleteDeviceQuota(scope)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </template>
              <template v-else>
                <div style="width:100%;height:20px;text-align:center;">
                  <span style="color: #1f2d3d;font-size: 12px">暂未添加设备指标</span>
                </div>
              </template>
            </el-row>
            <el-row>
              <div align="center" style="margin: 0 auto;padding-top: 10px">
                <el-button size="small" type="primary" @click="handleAddDeviceQuota">添加设备指标</el-button>
              </div>
            </el-row>
          </el-collapse-item>
        </template>
      </el-collapse>
      <el-dialog
        :visible.sync="dialogVisible"
        :title="dialogType==='edit'?'更新设备指标':'添加设备指标'"
      >
        <el-form
          ref="deviceQuotaForm"
          :model="deviceQuotaForm"
          :rules="(dialogType==='edit')?updateRules:addRules"
        >
          <el-row>
            <el-col :span="10">
              <el-form-item label="设备ID" label-width="100px" prop="deviceId">
                <el-input v-model="deviceQuotaForm.deviceId" disabled type="text" />
              </el-form-item>
            </el-col>
            <el-col :span="14">
              <el-form-item label="设备名" label-width="70px" prop="deviceName">
                <el-input v-model="deviceQuotaForm.deviceName" disabled type="text" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-form-item label="指标名" label-width="100px" prop="name">
              <el-input v-model="deviceQuotaForm.name" :disabled="dialogType==='edit'" type="text" placeholder="请输入指标名" />
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="主题" label-width="100px" prop="subject">
              <el-input v-model="deviceQuotaForm.subject" :disabled="dialogType==='edit'" type="text" placeholder="请输入指标主题" />
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="键名" label-width="100px" prop="valueKey">
              <el-input v-model="deviceQuotaForm.valueKey" :disabled="dialogType==='edit'" type="text" placeholder="请输入键名" />
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="键值类型" label-width="100px" prop="valueType">
              <el-select v-model="deviceQuotaForm.valueType" style="width: 100px;" :disabled="dialogType==='edit'" placeholder="请选择">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="单位" label-width="100px" prop="unit">
              <el-input v-model="deviceQuotaForm.unit" type="text" placeholder="请输入单位" />
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="webhook" label-width="100px" prop="webhook">
              <el-input v-model="deviceQuotaForm.webhook" type="text" placeholder="请输入webhook" />
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="参考值" label-width="100px" prop="reference">
              <el-input v-model="deviceQuotaForm.reference" type="text" placeholder="请输入参考值" />
            </el-form-item>
          </el-row>

          <div style="text-align:right;">
            <el-button v-loading="loading" type="danger" @click="handleCancel">取消</el-button>
            <el-button v-loading="loading" type="primary" @click="confirm">确认</el-button>
          </div>
        </el-form>
      </el-dialog>
    </div>

    <div class="page-container">
      <el-pagination
        :current-page="deviceQuotaPage.page"
        :page-size="deviceQuotaPage.pageSize"
        :page-count="deviceQuotaPage.pages"
        :total="deviceQuotaPage.counts"
        :pager-count="deviceQuotaPage.pageCount"
        align="center"
        layout="prev, pager, next, jumper"
        @current-change="handlePageChange"
        @prev-click="handlePageChange"
        @next-click="handlePageChange"
      />
    </div>
  </div>
</template>

<script>
import { addQuota, delQuota, findDeviceQuotaPage, updateQuota } from '@/api/quota'
import { parseTime } from '@/utils'

const defaultDeviceQuotaPage = {
  page: 1,
  pageSize: 5,
  pageCount: 9
}
const defaultQuotaForm = {
  deviceId: '',
  deviceName: '',
  quotaId: '',
  name: '',
  unit: '',
  number: '',
  subject: '',
  valueKey: '',
  valueType: '',
  webhook: '',
  reference: ''
}
export default {
  name: 'DeviceQuotaManage',
  data() {
    return {
      loading: false,
      listLoading: true,
      dialogType: 'new',
      dialogVisible: false,
      deviceQuotaForm: Object.assign({}, defaultQuotaForm),
      Height: '',
      activeName: '1',
      stateOptions: [
        { key: -1, value: '-1', label: '无' },
        { key: 0, value: '0', label: '开启且在线' },
        { key: 1, value: '1', label: '关闭或离线' }
      ],
      options: [
        { key: 'number', value: 'number', label: 'number' },
        { key: 'boolean', value: 'boolean', label: 'boolean' }
      ],
      searchDeviceQuotaForm: { number: '', tag: '', state: '' },
      deviceQuotaPage: Object.assign({}, defaultDeviceQuotaPage),
      deviceQuotaList: [],
      addRules: {
        name: [{ required: true, message: '请输入指标名', trigger: 'blur' }],
        unit: [{ required: true, message: '请输入单位', trigger: 'blur' }],
        subject: [{ required: true, message: '请输入主题', trigger: 'blur' }],
        valueKey: [{ required: true, message: '请输入键名', trigger: 'blur' }],
        valueType: [{ required: true, message: '请输入键值类型', trigger: 'blur' }],
        webhook: [{ required: true, message: '请输入webhook', trigger: 'blur' }],
        reference: [{ required: true, message: '请输入参考值', trigger: 'blur' }]
      },
      updateRules: {
        unit: [{ required: true, message: '请输入单位', trigger: 'blur' }],
        webhook: [{ required: true, message: '请输入webhook', trigger: 'blur' }],
        reference: [{ required: true, message: '请输入参考值', trigger: 'blur' }]
      }
    }
  },
  watch: {
    '$route.query': {
      handler(newVal, oldVal) {
        console.log('newQuery', newVal)
        const query = this.$route.query
        if (Object.keys(newVal).length !== Object.keys(oldVal).length || (
          newVal.tag !== oldVal.tag || newVal.number !== oldVal.number || newVal.state !== oldVal.state
        )) {
          newVal.page = 1
          newVal.pageSize = 10
        }
        if (query.number) this.searchDeviceQuotaForm.number = query.number
        if (query.tag) this.searchDeviceQuotaForm.tag = query.tag
        if (query.state) this.searchDeviceQuotaForm.state = query.state
        findDeviceQuotaPage(query).then(response => {
          // console.log('pager', response.data.pager)
          this.updatePage(response.data.pager)
        })
        this.activeName = '1'
      },
      deep: true
    }
  },
  created() {
    const query = this.$route.query
    let data = {}
    if (query) {
      if (query.page) data.page = parseInt(query.page)
      if (query.pageSize) data.pageSize = parseInt(query.pageSize)
      if (query.number) data.number = this.searchDeviceQuotaForm.number = query.number
      if (query.tag) data.tag = this.searchDeviceQuotaForm.tag = query.tag
      if (query.state) data.state = this.searchDeviceQuotaForm.state = query.state
    } else {
      data = { page: 1, pageSize: 10 }
    }
    findDeviceQuotaPage(data).then(response => {
      console.log('pager', response.data.pager)
      this.updatePage(response.data.pager)
    })
  },
  mounted() {
    document.getElementsByClassName('el-pagination__jump')[0].childNodes[0].nodeValue = '跳转第'
    document.getElementsByClassName('el-pagination__jump')[0].insertAdjacentText('beforeend', '页')
  },
  methods: {
    async delDeviceQuota(index, row) {
      console.log('row', row)
      await delQuota(row)
      console.log('index', index)
      const data = this.deviceQuotaList[parseInt(this.activeName)]
      data.quotaList.splice(index, 1)
      this.$message({
        type: 'success',
        message: '删除成功!'
      })
    },
    addDeviceQuota() {
      this.$refs.deviceQuotaForm.validate(async valid => {
        if (valid) {
          this.loading = true
          // console.log('deviceQuotaForm', this.deviceQuotaForm)
          await addQuota(this.deviceQuotaForm).then(response => {
            const quota = response.data.quota
            console.log('quota', quota)
            const data = this.deviceQuotaList[parseInt(this.activeName)]
            data.quotaList.push(quota)
          })
          this.loading = false
        } else {
          console.log('error update!!')
          return false
        }
      })
    },
    updateDeviceQuota() {
      this.$refs.deviceQuotaForm.validate(valid => {
        if (valid) {
          this.loading = true
          updateQuota(this.deviceQuotaForm)
          this.loading = false
        } else {
          console.log('error update!!')
          return false
        }
      })
    },
    handleAddDeviceQuota() {
      this.dialogType = 'new'
      this.deviceQuotaForm = Object.assign({}, defaultQuotaForm)
      const data = this.deviceQuotaList[parseInt(this.activeName)]
      this.deviceQuotaForm.deviceId = data.id
      this.deviceQuotaForm.deviceName = data.name
      this.deviceQuotaForm.number = data.number
      this.dialogVisible = true
      // console.log('handleAdd', this.deviceQuotaForm)
    },
    handleUpdateDeviceQuota(scope) {
      this.dialogType = 'edit'
      const data = this.deviceQuotaList[parseInt(this.activeName)]
      this.deviceQuotaForm = Object.assign({}, defaultQuotaForm)
      for (const key of Object.keys(this.deviceQuotaForm)) {
        if (scope.row[key]) this.deviceQuotaForm[key] = scope.row[key]
      }
      this.deviceQuotaForm.quotaId = scope.row.id
      this.deviceQuotaForm.deviceId = data.id
      this.deviceQuotaForm.deviceName = data.name
      this.deviceQuotaForm.number = data.number
      // console.log('handle-update', data, this.deviceQuotaForm)
      this.dialogVisible = true
    },
    handleDeleteDeviceQuota({ $index, row }) {
      this.$confirm('是否移除该指标?', 'Warning', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await this.delDeviceQuota($index, row)
      }).catch(err => {
        console.error(err)
      })
    },
    handleCancel() {
      this.deviceQuotaForm = Object.assign({}, defaultQuotaForm)
      this.dialogVisible = false
    },
    async confirm() {
      const isEdit = this.dialogType === 'edit'
      console.log('deviceQuotaForm', this.deviceQuotaForm)
      if (!isEdit) {
        await this.addDeviceQuota()
      } else {
        await this.updateDeviceQuota()
        let flag = true
        for (let i = 0; flag && i < this.deviceQuotaList.length; i++) {
          if (this.deviceQuotaList[i].number === this.deviceQuotaForm.number) {
            const list = this.deviceQuotaList[i].quotaList
            // console.log('list', list)
            for (let j = 0; flag && j < list.length; j++) {
              if (this.deviceQuotaForm.quotaId === list[j].id) {
                this.deviceQuotaList[i].quotaList[j].unit = this.deviceQuotaForm.unit
                this.deviceQuotaList[i].quotaList[j].webhook = this.deviceQuotaForm.webhook
                this.deviceQuotaList[i].quotaList[j].reference = this.deviceQuotaForm.reference
                flag = false
              }
            }
          }
        }
      }
      this.dialogVisible = false
    },
    searchPage() {
      let data = Object.assign({}, this.searchDeviceQuotaForm)
      data = Object.assign(data, this.deviceQuotaPage)
      console.log('searchParam', data)
      delete data['counts']
      this.$router.replace({
        path: this.$route.path,
        query: this.simplify(data)
      })
    },
    updatePage(pager) {
      this.deviceQuotaPage = {
        page: pager.page,
        pages: pager.pages,
        pageSize: pager.pageSize,
        counts: pager.counts
      }
      this.deviceQuotaList = pager.items
      this.listLoading = false
    },
    simplify(obj) {
      const res = Object.assign({}, obj)
      for (const key of Object.keys(res)) {
        if (res[key] === '') delete res[key]
      }
      return res
    },
    handlePageChange(param) {
      this.deviceQuotaPage.page = param
      const data = Object.assign({}, this.deviceQuotaPage)
      delete data['counts']
      if (this.searchDeviceQuotaForm.number) data.number = this.searchDeviceQuotaForm.number
      if (this.searchDeviceQuotaForm.tag) data.tag = this.searchDeviceQuotaForm.tag
      if (this.searchDeviceQuotaForm.state) data.state = this.searchDeviceQuotaForm.state
      this.$router.replace({
        path: this.$route.path,
        query: this.simplify(data)
      })
    },
    handleChange(val) {
      // console.log('val', val)
    },
    formatTime(time) {
      const format = '{y}-{m}-{d}'
      return parseTime(time, format)
    }
  }
}
</script>

<style scoped>

.search-container {
  width: 100%;
  height: 50px;
}

.table-container {
  width: 100%;
}

.page-container {
  width: 100%;
}

/deep/ .el-collapse-item__header {
  height: 65px;
  line-height: 30px;
}

/deep/ .el-collapse-item__content {
  padding-bottom: 5px;
  font-size: 13px;
  color: #FFFFFF;
}

</style>
